package cn.usian.filter;

import cn.usian.common.R;
import com.alibaba.fastjson.JSON;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")//表示servlet的拦截器的注解 webServlet
public class LoginFilter implements Filter {
    private AntPathMatcher antPathMatcher=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.将request和response转成带http请求
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        //2.获取请求路径
        String uri = request.getRequestURI();
        //3.声明需要放行的路径
        String []urls={"/backend/**","/employee/login"};
        //4.判定请求路径是否在放行路径中
        boolean result=checkUrl(urls,uri);
        if (result){
            //直接放行
            filterChain.doFilter(request,response);
            return;
        }
        //5.判定是否登录
        //从session获取登录数据
        HttpSession session=request.getSession();
        Object employee=session.getAttribute("employee");
        if (employee!=null){
            filterChain.doFilter(request,response);
            return;
        }
        //6.用户没有登录
        String jsonString = JSON.toJSONString(R.error("NOTLOGIN"));
        //7.将r对象直接响应
        response.getWriter().write(jsonString);

    }
    public boolean checkUrl(String []urls,String uri){
        for (String url:urls){
            if (antPathMatcher.match(url,uri)){
                return true;
            }
        }
        return false;
    }
}
